package com.val.pptx;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	
	private final String KEY_ESC = "1";
	private final String KEY_PLAY = "SHIFT+F5";  // 组合键
	private final String KEY_PREV= "105";
	private final String KEY_NEXT = "106";
	
	private TextView tv_msg;
	private EditText et_addr;
	private ImageButton btn_play;
	private Handler handler = new Handler();
	
	final int SERVERPORT = 2015;
	private Socket connfd;
	private OutputStream os;
	
	private boolean isConnected = false, isDisplay = false;
	private AudioManager mAudioManager; 
	private MenuItem menuItem;
	
	// 保持屏幕常亮
	PowerManager powerManager = null;
    WakeLock wakeLock = null;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 设置屏幕常亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        tv_msg = (TextView) findViewById(R.id.show_msg);
        btn_play = (ImageButton) findViewById(R.id.btn_play);
        
       
        
        /* 屏蔽音量键 */
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.setSpeakerphoneOn(false);
        setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);   
        mAudioManager.setMode(AudioManager.MODE_IN_CALL);
        
        /* 获取和设置结束 */
        
		btn_play.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				System.out.println("Debug-->btn_play");
				if (!isDisplay) {
					sendCode(connfd, os, KEY_PLAY);
					btn_play.setImageResource(com.val.pptx.R.drawable.btn_stop_style);
					isDisplay = !isDisplay;
				} else {
					sendCode(connfd, os, KEY_ESC);
					btn_play.setImageResource(com.val.pptx.R.drawable.btn_play_style);
					isDisplay = !isDisplay;
				}
			}
		});

    }

    /* 创建菜单按钮 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_add:
            	if (!isConnected) {
            		menuItem = item;
	            	showAddDlg();
            	} else {
            		showDelDlg();
            	}
                return true;
                
            case R.id.action_about:
            	showAboutDlg();
            	return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    // 重写onAttachedToWindow()，用于屏蔽使用音量键时调节音量
	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); // 设置窗口类型
	}
    
	// 此处返回true，和上面重写的onAttachedToWindow()一起完成屏蔽使用音量键时调节音量
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitDlg();
			return false;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			event.startTracking(); 
			//Toast.makeText(this.getApplicationContext(), "屏蔽音量+", Toast.LENGTH_SHORT).show();
			if (isDisplay) {
				sendCode(connfd, os, KEY_PREV);
				
			}
			
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
			event.startTracking(); 
			//Toast.makeText(this.getApplicationContext(), "屏蔽音量-", Toast.LENGTH_SHORT).show();
			if (isDisplay) {
				sendCode(connfd, os, KEY_NEXT);
				
			}
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

    /* 显示关于对话框 */
    private void showAboutDlg() {
		AlertDialog dlg_about = new AlertDialog.Builder(this).create();
		dlg_about.setTitle("关于");
		// 自定义View，用于修改.setMessage()内容的大小
		LayoutInflater factory=LayoutInflater.from(MainActivity.this);
		final View DialogView=factory.inflate(R.layout.about_dlg, null);
		dlg_about.setView(DialogView);
		dlg_about.show();
    }
    
    /* 显示"添加远程设备"IP的对话框 */
    private void showAddDlg() {
		AlertDialog addRemoteAdd = new AlertDialog.Builder(this).create();
    	addRemoteAdd.setTitle("请输入远程IP地址");
    	et_addr = new EditText(this);
    	addRemoteAdd.setView(et_addr);
    	addRemoteAdd.setButton( AlertDialog.BUTTON_POSITIVE, "取消", addRmtAddrListener);
    	addRemoteAdd.setButton(AlertDialog.BUTTON_NEGATIVE, "连接", addRmtAddrListener);
    	addRemoteAdd.show();
    }
    
    /* 显示删除远程设备的确认对话框 */
	private void showDelDlg() {
		AlertDialog addRemoteAdd = new AlertDialog.Builder(this).create();
    	addRemoteAdd.setTitle("提示");
    	addRemoteAdd.setMessage("已连接远程设备，是否要断开？");
    	addRemoteAdd.setButton( AlertDialog.BUTTON_POSITIVE, "否", delRmtAddrListener);
    	addRemoteAdd.setButton(AlertDialog.BUTTON_NEGATIVE, "是", delRmtAddrListener);
    	addRemoteAdd.show();
	}
	
	/* 显示退出确认对话框 */
	private void showExitDlg() {
		AlertDialog isExit = new AlertDialog.Builder(this).create();
		isExit.setTitle("提示");
		isExit.setMessage("确定要退出程序吗？");
		isExit.setButton( AlertDialog.BUTTON_POSITIVE, "取消", exitListener);
		isExit.setButton(AlertDialog.BUTTON_NEGATIVE, "确定", exitListener);
		isExit.show();
    }
    
	/* "添加远程设备"按钮的监听器 */
	DialogInterface.OnClickListener addRmtAddrListener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_NEGATIVE:// 按下“连接”键
				System.out.println("Debug-->InSure Button clicked");
				
				if (et_addr.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(), "请输入远程IP地址", 
							Toast.LENGTH_SHORT).show();
				} else {
					dialog = ProgressDialog.show(MainActivity.this, null,
							"连接中，请稍候", true, true);
					
					handler.post(new Runnable() {
						
						@Override
						public void run() {
							String server_ip = et_addr.getText().toString();
							boolean isConn = InitConn(server_ip);
							if (isConn) {
								tv_msg.setText("已连接远程设备");
								menuItem.setTitle("删除设备");
								btn_play.setVisibility(View.VISIBLE);
								isConnected = !isConnected;
								
							} else {
								
								Toast.makeText(getApplicationContext(),"请输入重新输入远程IP地址", Toast.LENGTH_LONG).show();
								System.out.println("Debug-->isConn = " + isConn);
							}
						}
					});					
					dialog.dismiss();
				}
				
				break;
				
			case AlertDialog.BUTTON_POSITIVE:// 按下“取消”键
				break;

			default:
				break;
			}
		}
	};

	/* 删除远程设备按钮的监听器 */
	DialogInterface.OnClickListener  delRmtAddrListener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_NEGATIVE:// 按下“是”键
				try {
					os.close();
					connfd.close();
					if (isDisplay) {
						
						btn_play.setVisibility(View.GONE);
						btn_play.setImageResource(com.val.pptx.R.drawable.btn_play_style);
						isDisplay = !isDisplay;
					} else {
						btn_play.setVisibility(View.GONE);
					}
					isConnected = !isConnected;
					menuItem.setTitle("添加设备");
					tv_msg.setText("请先添加远程设备");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
				
			case AlertDialog.BUTTON_POSITIVE:// 按下“否”键
				break;

			default:
				break;
			}
		}
	};
	
	/* 退出程序的监听器 */
	DialogInterface.OnClickListener exitListener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_NEGATIVE:// 按下“确定”键
				
				getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
				mAudioManager.setSpeakerphoneOn(true); 
				finish();
				break;

			case AlertDialog.BUTTON_POSITIVE:// 按下“取消”键
				break;
			
			default:
				break;
			}
		}
	};
	
	/* 初始化连接 */
	private boolean InitConn(String server_ip) {
		connfd = new Socket();
        try {
        	System.out.println(server_ip + " " + SERVERPORT);
			connfd.connect(new InetSocketAddress(server_ip, SERVERPORT), 2000);
			os = connfd.getOutputStream();
			System.out.println("Debug--> Init conn");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return connfd.isConnected();
	}

	/* 向远程设备发送键盘码 */
	private void sendCode(Socket connfd, OutputStream os, String code) {

		try {
			os.write(code.getBytes("utf-8"));
			System.out.println("Debug--> code = " + code);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@Override
	protected void onStart() {
		super.onStart();
		
		setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
		mAudioManager.setMode(AudioManager.MODE_IN_CALL);  
		mAudioManager.setSpeakerphoneOn(false);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		setVolumeControlStream(AudioManager.MODE_NORMAL);   
		mAudioManager.setMode(AudioManager.MODE_NORMAL);  
		mAudioManager.setSpeakerphoneOn(false);
	}
	
	@Override
    protected void onDestroy() {
    	super.onDestroy();
    	
    	try {
    		if (isConnected) {
    			os.close();
    			connfd.close();
    		}
    		getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			mAudioManager.setSpeakerphoneOn(true); 
    		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
    }
    
}
